package com.creditease.shield.flow.netty;

import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.timeout.IdleStateHandler;

@Component
public class JavaNettyServerChannelInitializer extends ChannelInitializer<SocketChannel> {
	
	@Resource
	private FlowNoServerHandler flowNoServerHandler;
	
	@Override
	protected void initChannel(final SocketChannel ch) throws Exception {
		//每隔60s的时间内如果没有接受到任何的read事件的话，则会触发userEventTriggered事件，并指定IdleState的类型为READER_IDLE
		ch.pipeline().addLast(new IdleStateHandler(60, 0, 0, TimeUnit.SECONDS));
		//因为我们在client端设置了每隔30s会发送一个心跳包过来，如果60s都没有收到心跳，则说明链路发生了问题
		ch.pipeline().addLast(new AcceptorIdleStateTrigger());
		ch.pipeline().addLast(new ObjectEncoder());
		ch.pipeline().addLast(new ObjectDecoder(1024*1024,ClassResolvers.cacheDisabled(this.getClass().getClassLoader())));
		ch.pipeline().addLast(flowNoServerHandler);
	}
}
